<?php

namespace Lib\PayApi\Cai1Pay;
use Lib\Utils\Utils;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/22
 * Time: 1:36
 */
class PaymentClient {
    public static function pay($orderNo, $money, $pbank) {
        $cai1Pay = C('Cai1Pay');
        $Date = date('Ymd');
        $requestArray = array(
            "form_url" => $cai1Pay['form_url'],
            "Mer_code" => $cai1Pay['Mer_code'],
            "Billno" => $orderNo,
            "Amount" => sprintf("%.2f", $money),
            "Date" => date('Ymd'),
            "Currency_Type" => $cai1Pay['Currency_Type'],
            "Gateway_Type" => $pbank,
            "Lang" => $cai1Pay['Lang'],
            "Merchanturl" => $cai1Pay['returnUrl'],
            "OrderEncodeType" => $cai1Pay['OrderEncodeType'],
            "RetEncodeType" => $cai1Pay['RetEncodeType'],
            "Rettype" => $cai1Pay['Rettype'],
            "ServerUrl" => $cai1Pay['notifyUrl'],
        );
        $SignMD5 = md5($orderNo . sprintf("%.2f", $money) . $Date . $cai1Pay['Currency_Type'] . $cai1Pay['Mer_key']);
        $requestArray["SignMD5"] = $SignMD5;

        return $requestArray;
    }

    private static function udate($format = 'u', $utimestamp = null) {
        if (is_null($utimestamp))
            $utimestamp = microtime(true);

        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);

        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }

    public static function query($orderNo) {
        $cai1Pay = C('Cai1Pay');
        $requestarray = array(
            "id" => $cai1Pay['merchantId'],
            "appid" => $cai1Pay['appid'],
            "key" => $cai1Pay['key'],
        );

        $md5str = "";
        foreach ($requestarray as $key => $val) {
            $md5str = $md5str . $val ;
        }
        $sign = md5($md5str);

        $requestarray["posttime"] = self::udate("YmdHiZ");
        $requestarray["orderId"] = $orderNo;//date("YmdHis");
        $requestarray["sign"] = $sign;
        return Utils::post($cai1Pay['findUri'], $requestarray);
    }
}